const config = require('config')
const axios = require('axios')

const appKey = config.get('push.appKey')

const masterKey = config.get('push.masterKey')

const tmpKey = Buffer.from(`${appKey}:${masterKey}`) 

const key = tmpKey.toString('base64')

axios.defaults.baseURL = 'https://api.jpush.cn/v3'
axios.defaults.headers.common['Authorization'] = `Basic ${key}`

module.exports = class PushProxy {
  static async push (task) {
    const { id, name } = task
    const params = {
      platform: ['android'],
      audience: 'all',
      notification: {
        android: {
          alert: '通知',
          title: name,
          extras: {
            id
          }
        }
      }
    }
    try {
      const result = await this.validate(params)
      const { status } = result
      if (status === 200) {
        return axios.post('/push', params)
      }
    } catch (e) {
      console.log(e)
    }
  }

  static async validate (params) {
    return axios.post('/push/validate', params)
  }
}
